const Region = require('../models/Region');
const catchAsync = require('../middleware/catchAsync');
const AppError = require('../utils/appError');

// 获取所有区域
exports.getAllRegions = catchAsync(async (req, res, next) => {
    try {
        console.log('获取所有区域请求');
        const regions = await Region.findAll();
        console.log('获取到的区域列表:', regions);
        res.json({ data: regions });
    } catch (error) {
        console.error('获取区域列表失败:', error);
        next(error);
    }
});

// 获取单个区域
exports.getRegion = catchAsync(async (req, res, next) => {
    try {
        const regionId = parseInt(req.params.id);
        console.log('获取区域详情，ID:', regionId);
        
        if (isNaN(regionId) || regionId <= 0) {
            return res.status(400).json({ message: '无效的区域ID' });
        }

        const region = await Region.findById(regionId);
        console.log('查询结果:', region);
        
        if (!region) {
            return res.status(404).json({ message: '区域不存在' });
        }

        res.json({ data: region });
    } catch (error) {
        console.error('获取区域详情失败:', error);
        next(error);
    }
});

// 创建区域
exports.createRegion = catchAsync(async (req, res, next) => {
    try {
        const { name, code, level, parent_id, status, manager_id } = req.body;
        
        // 验证必填字段
        if (!name || !code || !level) {
            return res.status(400).json({ message: '名称、编码和级别为必填项' });
        }

        // 检查编码是否已存在
        const existingRegion = await Region.findByCode(code);
        
        if (existingRegion) {
            return res.status(400).json({ message: '区域编码已存在' });
        }

        const regionId = await Region.create({
            name,
            code,
            level,
            parent_id,
            status: status || 'active',
            manager_id
        });

        res.status(201).json({
            message: '区域创建成功',
            data: { id: regionId, ...req.body }
        });
    } catch (error) {
        console.error('创建区域失败:', error);
        next(error);
    }
});

// 更新区域
exports.updateRegion = catchAsync(async (req, res, next) => {
    try {
        const regionId = parseInt(req.params.id);
        const { name, code, level, parent_id, status, manager_id } = req.body;

        console.log('更新区域请求数据:', {
            regionId,
            name,
            code,
            level,
            parent_id,
            status,
            manager_id
        });

        if (isNaN(regionId) || regionId <= 0) {
            return res.status(400).json({ message: '无效的区域ID' });
        }

        // 验证必填字段
        if (!name || !code || !level) {
            return res.status(400).json({ message: '名称、编码和级别为必填项' });
        }

        // 检查编码是否被其他区域使用
        const codeExists = await Region.checkCodeExists(code, regionId);
        if (codeExists) {
            return res.status(400).json({ message: '区域编码已存在' });
        }

        // 验证状态值
        let validStatus = 'active';
        if (status !== undefined) {
            if (typeof status === 'number') {
                validStatus = status === 1 ? 'active' : 'inactive';
            } else if (typeof status === 'string') {
                if (status !== 'active' && status !== 'inactive') {
                    console.log('无效的状态值:', status);
                    return res.status(400).json({ message: '状态值无效，必须是 active 或 inactive' });
                }
                validStatus = status;
            } else {
                console.log('无效的状态值类型:', typeof status);
                return res.status(400).json({ message: '状态值类型无效' });
            }
        }

        const success = await Region.update(regionId, {
            name,
            code,
            level,
            parent_id,
            status: validStatus,
            manager_id
        });

        if (!success) {
            return res.status(404).json({ message: '区域不存在' });
        }

        res.json({
            message: '区域更新成功',
            data: { id: regionId, ...req.body }
        });
    } catch (error) {
        console.error('更新区域失败:', error);
        next(error);
    }
});

// 删除区域
exports.deleteRegion = catchAsync(async (req, res, next) => {
    try {
        const regionId = parseInt(req.params.id);

        if (isNaN(regionId) || regionId <= 0) {
            return res.status(400).json({ message: '无效的区域ID' });
        }

        // 检查区域是否存在
        const region = await Region.findById(regionId);
        if (!region) {
            return res.status(404).json({ message: '区域不存在' });
        }

        // 检查是否有子区域
        const hasChildren = await new Promise((resolve, reject) => {
            Region.hasChildren(regionId, (err, result) => {
                if (err) reject(err);
                resolve(result);
            });
        });

        if (hasChildren) {
            return res.status(400).json({ message: '该区域下存在子区域，无法删除' });
        }

        const success = await Region.delete(regionId);
        if (!success) {
            return res.status(404).json({ message: '区域不存在' });
        }

        res.json({ message: '区域删除成功' });
    } catch (error) {
        next(error);
    }
});

// 设置区域负责人
exports.setRegionManager = catchAsync(async (req, res, next) => {
    try {
        const regionId = parseInt(req.params.id);
        const { manager_id } = req.body;

        if (isNaN(regionId) || regionId <= 0) {
            return res.status(400).json({ message: '无效的区域ID' });
        }

        if (!manager_id) {
            return res.status(400).json({ message: '负责人ID不能为空' });
        }

        const success = await Region.setManager(regionId, manager_id);
        if (!success) {
            return res.status(404).json({ message: '区域不存在' });
        }

        res.json({ message: '区域负责人设置成功' });
    } catch (error) {
        next(error);
    }
}); 